// bridge.js - 运行在 ISOLATED 环境，可访问 chrome.runtime

window.addEventListener('message', async (event) => {
  // 确保消息来自自己的插件
  if (event.source !== window) return;

  const { type } = event.data;
  if (type === 'GET_TESSERACT_URLS') {
    try {
      const workerPath = await sendMessageToBackground('lib/worker.min.js');
      const corePath = await sendMessageToBackground('lib/tesseract-core.wasm.min.js');
      const langPath = await sendMessageToBackground('lib/traineddata/');

      // 回传给 MAIN world
      window.postMessage({
        type: 'TESSERACT_URLS_RESPONSE',
        data: { workerPath, corePath, langPath }
      }, '*');
    } catch (err) {
      window.postMessage({
        type: 'TESSERACT_URLS_ERROR',
        error: err.message
      }, '*');
    }
  }
});

function sendMessageToBackground(path) {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(
      {
        type: 'GET_RESOURCE_URL',
        path
      },
      (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response.url);
        }
      }
    );
  });
}